<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use Goutte\Client;
use GuzzleHttp\Client as GuzzleClient;
use App\Models\Article;

class FetchPDF extends Command
{

    const DOWNLOAD_URL_PREFIX = 'http://www.zoores.ac.cn/EN/article/downloadArticleFile.do';

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fetch:pdf {id?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $id = $this->argument('id');

        if ($id) {
            $this->downloadPDF(Article::where('zr_id', $id)->first());
        } else {
            $page = 1;
            $count = 0;
            while (true) {
                $articles = Article::simplePaginate(5, ['*'], 'page', $page);
                $break = (bool)(count($articles->items()) == 0);
                foreach ($articles as $article) {
                    $this->downloadPDF($article);
                    $count++;
                }

                if ($break) break;
                $page++;
                $this->info($count++ . 'th articles pdf fetched.');
            }
        }
    }


    public function downloadPDF($article)
    {
        $id = $article->zr_id;
        try{
            $client = new Client();
            $guzzleClient = new GuzzleClient(array(
                'timeout' => 60,
            ));
            $client->setClient($guzzleClient);


            $this->info('ZR ID: ' . $id . ',  ' . $article->id . ' start');
            $file = public_path('uploads/' . config('admin.upload.directory.file')) . '/' . 'zr_' . $article->id . '.pdf';

            if (!file_exists($file) || (filesize($file)/1024 < 5)) {
                $url = self::DOWNLOAD_URL_PREFIX . '?' . http_build_query(['id' => $id, 'attachType' => 'PDF']);
                $response = $client->getClient()->get($url, [
                    'save_to' => $file
                ]);

                $this->error(filesize($file));
                Article::where('id', $article->id)
                    ->update([
                        'pdf' => config('admin.upload.directory.file') . '/' . 'zr_' . $article->id . '.pdf'
                    ]);


                $this->info('ZR ID: ' . $id . ',  ' . $article->id . ' PDF download [' . $response->getStatusCode() .  ']' . $response->getReasonPhrase());
            } else {
                $this->info('Skip ZR ID: ' . $id . ', real id: ' . $article->id);
            }

        } catch(\Exception $e) {
            echo $e->getMessage(); exit;
        }
    }
}
